package Service.Impl;

import Service.UserService;
import model.User;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

import static init.UserInit.users;


public class UserServiceImpl implements UserService {
    @Override
    public boolean userLogin(String userName, String password) {
        for(User user:users){
            if (userName.equals(user.getUsername()) && password.equals(user.getPassword())){
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean userRegister(String userName, String password,int age,String phone,double money) {
        if (StringUtils.isEmpty(userName) && StringUtils.isEmpty(password)){
            return false;
        }
        User user = new User(666,userName,password,age,phone,money);
        users.add(user);
        try {
            BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("user.txt", StandardCharsets.UTF_8, true));
            String txt = "666"+","+userName+","+password+","+age+","+phone+","+money;
            bufferedWriter.newLine();
            bufferedWriter.write(txt);
            bufferedWriter.newLine();
            System.out.println("用户信息已保存");
            bufferedWriter.close();
        } catch (IOException e) {
            System.out.println("写入信息错误");
            throw new RuntimeException(e);
        }
        return true;
    }
}
